import java.io.File;
import java.util.ArrayList;


public class GuiManager
{
	static GuiManager GM;
	static GUI g;
	static ActionManager t;
	private boolean AMActive;
	ArrayList<Message> msgQueue;
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		Log.init();
		GM=new GuiManager();
		GM.init();
		GM.start();
	}
	
	public void init()
	{
		g=new GUI();
		t=new ActionManager();
		g.init(this,t);
		t.init();
		msgQueue=new ArrayList<Message>();
		setInitialized();
	}
	
	public void start()
	{
		g.start();
		t.start();
		Message msg;
		while (params.isActive)
		{
			while (!msgQueue.isEmpty())
			{
				msg=msgQueue.remove(0);
				handleMessage(msg);
			}
			
			if (AMActive && !t.isActive()) // a message indicating ActionManger is working received. check periodically if it has finished
			{
				AMActive=false;
				g.enableButtons();				
			}
			try {
				Thread.sleep(100);
			} catch (Exception e) {
				Log.writeEx(e);
			}
		}		
	}
	
	private void handleMessage(Message msg)
	{
		if (msg.getSubject()==MsgCommands.ACTIONACTIVE)
			AMActive=true;
		else if (msg.getSubject()==MsgCommands.WRITE)
			g.consoleWrite(msg.getBody());
		else
			Log.error("Unknown message command Recieved in GuiManager. cmd:"+msg.getSubject().toString());
	}

	public void pushMessage(Message msg)
	{
		msgQueue.add(msg);
	}
	
	public void setInitialized()
	{
		params.isInitialized=isProjectExists();
	}
	
	public boolean isProjectExists()
	{
		File sys=new File(params.activeProject,"system");
		if (!sys.isDirectory())
			return false;
		if (sys.listFiles().length>0)
			return true;
		else
			return false;
	}

	public static GuiManager getInstance()
	{
		return GM;
	}
}
